<!-- 下拉菜单组件 - 提供可复用的下拉菜单交互功能 -->
<template>
  <div class="dropdown-menu-container" ref="containerRef">
    <!-- 触发下拉菜单的按钮/标题 -->
    <div 
      class="dropdown-trigger"
      @click="toggleMenu"
      :class="{ 'disabled': disabled }"
      :style="{ width: width + 'px' || 'auto' }"
    >
      <!-- 使用插槽允许自定义触发内容 -->
      <slot name="trigger">
        <span class="trigger-text">{{ title }}</span>
        <i 
          class="arrow" 
          :class="{ 'rotate': isOpen }"
          v-if="showArrow"
        ></i>
      </slot>
    </div>

    <!-- 下拉菜单内容 -->
    <Teleport to="body">
      <Transition name="dropdown">
        <div 
          v-if="isOpen && !disabled"
          class="dropdown-content"
          :class="position"
          ref="menuRef"
          @click.stop
        >
          <!-- 默认菜单项渲染 -->
          <template v-if="items && items.length > 0">
            <div 
              v-for="(item, index) in items" 
              :key="index"
              class="dropdown-item"
              :class="{ 'active': activeIndex === index }"
              @click="handleItemClick(item, index)"
              @keydown.up.prevent="handleKeyDown(index, -1)"
              @keydown.down.prevent="handleKeyDown(index, 1)"
              @keydown.enter.prevent="handleItemClick(item, index)"
              @keydown.esc.prevent="closeMenu"
            >
              <!-- 菜单项插槽 -->
              <slot name="item" :item="item" :index="index">
                <span class="item-content">
                  <i v-if="item.icon" class="item-icon">{{ item.icon }}</i>
                  <span class="item-text">{{ item.name }}</span>
                </span>
              </slot>
            </div>
          </template>
          
          <!-- 自定义内容插槽 -->
          <slot></slot>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'

// 菜单项类型定义
export interface DropdownItem {
  id: string
  name: string
  icon?: string
  [key: string]: any // 允许额外的自定义属性
}

// Props 定义 - 使用withDefaults来设置默认值，避免重复调用
const props = withDefaults(defineProps<{
  // 下拉菜单标题
  title: string
  // 菜单项数组
  items?: DropdownItem[]
  // 下拉菜单位置
  position?: 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'
  // 下拉菜单宽度
  width?: number
  // 是否禁用
  disabled?: boolean
  // 是否显示箭头
  showArrow?: boolean
  // 点击菜单项后是否自动关闭
  autoClose?: boolean
}>(), {
  position: 'bottom-left',
  disabled: false,
  showArrow: true,
  autoClose: true
})

// 事件定义
const emit = defineEmits<{
  // 点击菜单项时触发
  'item-click': [item: DropdownItem, index: number]
  // 下拉菜单打开时触发
  open: []
  // 下拉菜单关闭时触发
  close: []
}>()

// 响应式数据
const isOpen = ref(false)
const activeIndex = ref(-1)
const containerRef = ref<HTMLElement>()
const menuRef = ref<HTMLElement>()

// 切换菜单显示状态
const toggleMenu = () => {
  if (props.disabled) return
  
  if (isOpen.value) {
    closeMenu()
  } else {
    openMenu()
  }
}

// 打开菜单
const openMenu = () => {
  isOpen.value = true
  activeIndex.value = -1
  
  // 触发打开事件
  emit('open')
  
  nextTick(() => {
    updatePosition()
  })
}

// 关闭菜单
const closeMenu = () => {
  isOpen.value = false
  activeIndex.value = -1
  
  // 触发关闭事件
  emit('close')
}

// 更新菜单位置
const updatePosition = () => {
  if (!containerRef.value || !menuRef.value) return
  
  const containerRect = containerRef.value.getBoundingClientRect()
  const menuEl = menuRef.value
  
  // 设置菜单位置样式
  menuEl.style.position = 'fixed'
  menuEl.style.zIndex = '1000'
  
  // 根据position prop设置菜单位置
  switch (props.position) {
    case 'bottom-left':
      menuEl.style.top = `${containerRect.bottom}px`
      menuEl.style.left = `${containerRect.left}px`
      break
    case 'bottom-right':
      menuEl.style.top = `${containerRect.bottom}px`
      menuEl.style.right = `${window.innerWidth - containerRect.right}px`
      break
    case 'top-left':
      menuEl.style.bottom = `${window.innerHeight - containerRect.top}px`
      menuEl.style.left = `${containerRect.left}px`
      break
    case 'top-right':
      menuEl.style.bottom = `${window.innerHeight - containerRect.top}px`
      menuEl.style.right = `${window.innerWidth - containerRect.right}px`
      break
  }
}

// 处理菜单项点击
const handleItemClick = (item: DropdownItem, index: number) => {
  // 触发点击事件
  emit('item-click', item, index)
  
  // 如果配置了自动关闭，则关闭菜单
  if (props.autoClose) {
    closeMenu()
  }
}

// 处理键盘导航
const handleKeyDown = (_currentIndex: number, direction: number) => {
  if (!props.items || props.items.length === 0) return
  
  // 初始化activeIndex
  if (activeIndex.value === -1) {
    activeIndex.value = direction > 0 ? 0 : props.items.length - 1
  } else {
    // 计算新的索引
    activeIndex.value = (activeIndex.value + direction + props.items.length) % props.items.length
  }
  
  // 滚动到选中项
  nextTick(() => {
    const items = menuRef.value?.querySelectorAll('.dropdown-item')
    if (items && activeIndex.value >= 0 && activeIndex.value < items.length) {
      (items[activeIndex.value] as HTMLElement).focus()
    }
  })
}

// 处理点击外部关闭菜单
const handleClickOutside = (event: MouseEvent) => {
  if (
    isOpen.value && 
    containerRef.value && 
    !containerRef.value.contains(event.target as Node) &&
    menuRef.value &&
    !menuRef.value.contains(event.target as Node)
  ) {
    closeMenu()
  }
}

// 监听窗口大小变化，更新菜单位置
const handleResize = () => {
  if (isOpen.value) {
    updatePosition()
  }
}

// 生命周期钩子
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  window.removeEventListener('resize', handleResize)
})
</script>











<style scoped>
/* 下拉菜单容器 */
.dropdown-menu-container {
  position: relative;
  display: inline-block;
}

/* 触发元素样式 */
.dropdown-trigger {
  /* 基本样式，可通过外部类覆盖 */
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  padding: 10px 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 0;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: background 0.3s ease;
  user-select: none;
}

/* 触发元素悬停效果 */
.dropdown-trigger:hover:not(.disabled) {
  background: linear-gradient(135deg, #556dd9 0%, #663da1 100%);
}

/* 禁用状态 */
.dropdown-trigger.disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background: #e0e0e0;
  color: #9e9e9e;
}

/* 触发元素文本 */
.trigger-text {
  font-size: 14px;
  font-weight: 500;
}

/* 箭头图标 */
.arrow {
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 6px solid white;
  transition: transform 0.3s ease;
}

/* 箭头旋转状态 */
.arrow.rotate {
  transform: rotate(180deg);
}

/* 下拉菜单内容容器 */
.dropdown-content {
  background: white;
  border-radius: 0;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  min-width: 120px;
  max-height: 300px;
  overflow-y: auto;
}

/* 菜单项样式 */
.dropdown-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-bottom: 1px solid #f0f0f0;
  text-align: left;
  font-size: 13px;
  color: #333;
  user-select: none;
  outline: none;
}

/* 移除最后一项的底部边框 */
.dropdown-item:last-child {
  border-bottom: none;
}

/* 菜单项悬停效果 */
.dropdown-item:hover,
.dropdown-item.active {
  background-color: #f8f9ff;
  color: #667eea;
  transform: translateX(2px);
  border-left: 3px solid #667eea;
  padding-left: 13px;
}

/* 菜单项点击效果 */
.dropdown-item:active {
  transform: scale(0.98);
  background-color: #e8ebff;
}

/* 菜单项内容 */
.item-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 菜单项图标 */
.item-icon {
  font-size: 14px;
  width: 16px;
  text-align: center;
}

/* 菜单项文本 */
.item-text {
  flex: 1;
}

/* 过渡动画 */
.dropdown-enter-active,
.dropdown-leave-active {
  transition: all 0.3s ease;
}

.dropdown-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.dropdown-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 滚动条样式 */
.dropdown-content::-webkit-scrollbar {
  width: 6px;
}

.dropdown-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.dropdown-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.dropdown-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dropdown-item {
    padding: 10px 12px;
    font-size: 12px;
  }
  
  .dropdown-trigger {
    padding: 8px 12px;
  }
  
  .trigger-text {
    font-size: 13px;
  }
}
</style>